<?php

//$Timer->start($_REQUEST[mode]);


if($_POST['act'] == 'addnew')
{
  $MySQLFuncColumns = array();
  $BreakColumns = array();
  $ImgFunc = array();
  foreach($_SQL_TABLE_FIELDS[$GlobPart] as $field => $farr)
  {
  	if($farr['type'] == 'image')
  	{
  		if($farr['useFTP'] == 'y')
  		{
  			require_once __CFG_PATH_LIBS.__CFG_PATH_CORE_CLASSES."class.FTPImage.php";
  			$ftpi = new FTPImage($farr['ftpServer'], $farr['ftpUserName'], $farr['ftpPassword'], $farr['ftpRootPath']);
  	
  			$farr['addVariable'] = $ftpi->addFieldHandler($field, $farr, $_FILES);
  			if($ftpi->hasErrors())
  			{
  				$ErrorFlag = __TRUE;
  				$ErrorMessages = array_merge($ErrorMessages, $ftpi->getErrorMessages());
  			}
  			if(!$farr['addVariable'])
  			{
  				$BreakColumns[] = $field;
  			}
  		}
  	}
    
    if(!isBlank($farr['required']) && !preg_match("/^".$farr['required']."$/Uis", $farr['addVariable']))
    {
      $ErrorFlag = __TRUE;
      $ErrorMessage = $ERRORS['admin'][__ERROR_INCORRECT_REQUIRED_FIELDS];
      $repl_arr = array('field' => $farr['title']);
      replaceVariables($repl_arr, $ErrorMessage);
      $ErrorMessages[] = $ErrorMessage;
    }
    elseif(!isBlank($farr['notEmptyRequired']) && !preg_match("/^".$farr['notEmptyRequired']."$/Uis", $farr['addVariable']) && !isBlank($farr['addVariable']))
    {
      $ErrorFlag = __TRUE;
      $ErrorMessage = $ERRORS['admin'][__ERROR_INCORRECT_REQUIRED_FIELDS];
      $repl_arr = array('field' => $farr['title']);
      replaceVariables($repl_arr, $ErrorMessage);
      $ErrorMessages[] = $ErrorMessage;
    }
    if($farr['listOfRelations'] == 'y')
    {      $ListOfRelations[] = &$_SQL_TABLE_FIELDS[$GlobPart][$field];
      $BreakColumns[] = $field;
    }
    elseif($farr['isRelation'] == 'y')
    {
      $Relations[] = &$_SQL_TABLE_FIELDS[$GlobPart][$field];
      $BreakColumns[] = $field;
    }
    elseif(!isBlank($farr['addVariable']) && isBlank($farr['listOfRelations']))
    {
      $result[$field] = $farr['addVariable'];
      if($farr['addVarType'] == $CONFIG['VarTypeSQLFunction'])
      {
      	$MySQLFuncColumns[] = $field;
      }
    }
    else
    {      $BreakColumns[] = $field;
    }

    if($farr['notUsedInDB'] == 'y')
    {
      $BreakColumns[] = $field;
    }
    if($farr['md5'] == 'y' && strlen($result[$field]) != 32)
    {
      $result[$field] = md5($result[$field]);
    }
    if($farr['unique'] == 'y')
    {
      $UniqueResult = getFieldByEnother($field, $WorkTable, $field, $result[$field]);
      if(stripslashes(trim($UniqueResult)) == stripslashes(trim($result[$field])))
      {        $ErrorFlag = __TRUE;
        $repl_arr = array('field' => $farr['title']);
        $ErrorMessage = $ERRORS['admin'][__ERROR_DUPLICATED_FIELD_VALUE];
        replaceVariables($repl_arr, $ErrorMessage);
        $ErrorMessages[] = $ErrorMessage;
      }
    }
  }

  if($ErrorFlag != __TRUE)
  {
    makeInsertList($strColumns, $strValues, $result, $MySQLFuncColumns, $BreakColumns);
    $InsID = insertItem($WorkTable, $strColumns, $strValues);
    if($_FLAGS['useImage'] == __TRUE)
    {      if(!isEmptyArr($ImgFunc))
      {
        foreach($ImgFunc as $n => $func)
        {
          eval($func);
        }
      }
    }

    if($WorkTableKeyFieldName != 'id')
    {      makeSearchList($strSet, $result, $MySQLFuncColumns, $BreakColumns);
      $newRow = getRowByStrSet($WorkTable, $strSet);
      $InsID = $newRow[$WorkTableKeyFieldName];
    }
    if(is_callable($CONFIG['AdminAddFuncAddItem']))
    {
      $NewRow = getRowByField($WorkTable, $WorkTableKeyFieldName, $InsID);
      eval($CONFIG['AdminAddFuncAddItem'].'();');
    }
    foreach($ListOfRelations as $n => $arr)
    {      if(isBlank($arr['tableInfo']['keyFieldCol']))
      {
        $arr['tableInfo']['keyFieldValue'] = $InsID;
      }
      else
      {        $arr['tableInfo']['keyFieldValue'] = getFieldByEnother($arr['tableInfo']['keyFieldCol'], $WorkTable, $WorkTableKeyFieldName, $InsID);
      }
      makeListOfRelations($arr['tableInfo'], $arr['addVariable']);
    }
    foreach($Relations as $n => $arr)
    {
      if(isBlank($arr['tableInfo']['keyFieldCol']))
      {
        $arr['tableInfo']['keyFieldValue'] = $InsID;
      }
      else
      {
        $arr['tableInfo']['keyFieldValue'] = getFieldByEnother($arr['tableInfo']['keyFieldCol'], $WorkTable, $WorkTableKeyFieldName, $InsID);
      }
      makeRelation($arr['tableInfo'], $arr['addVariable']);
    }
    if($_FLAGS['useImage'] == __TRUE || $_FLAGS['JVSCMessage'] == __TRUE)
    {
  	  go_toJVSC(getSameUri());
    }
    else
    {
      go_to(getSameUri());
    }
    exit();
  }
  else
  {   $tpl->assign('showAddNewForm', __TRUE);
   //$tpl->assign('ErrorMessage', $ErrorMessage);
   $tpl->assign('Item', $_POST);
  }
}
if($_POST['act'] == 'edit')
{
  foreach($_POST['item'] as $id => $val)
  {
    $MySQLFuncColumns = array();
    $BreakColumns = array();
    $result = array();
    foreach($_SQL_TABLE_FIELDS[$GlobPart] as $field => $farr)
    {
      if(!isBlank($farr['editVariable']) && $farr['useInListEdit'] == 'y')
      {
        $result[$field] = (is_array($farr['editVariable'])) ? $farr['editVariable'][$id] : $farr['editVariable'];
        if($farr['addVarType'] == $CONFIG['VarTypeSQLFunction'])
        {
      	  $MySQLFuncColumns[] = $field;
        }
      }
      elseif($farr['addVariable'] && !$farr['editVariable'] && $farr['useInListEdit'] == 'y')
      {
        $result[$field] = (is_array($farr['addVariable'])) ? $farr['addVariable'][$id] : $farr['addVariable'];
        if($farr['addVarType'] == $CONFIG['VarTypeSQLFunction'])
        {
      	  $MySQLFuncColumns[] = $field;
        }
      }
      elseif($farr['useInListEdit'] == 'y' && isBlank($farr['editVariable']) && isBlank($farr['addVariable']) && $farr['allowEmpty'] == 'y')
      {
        $result[$field] = $farr['addVariable'];
      }
      else
      {
        $BreakColumns[] = $field;
      }
    }
    if(is_callable($CONFIG['AdminAddFuncEditList']))
    {
      $OldRow = getRowByField($WorkTable, $WorkTableKeyFieldName, $id);
    }
    makeUpdateList($strSet, $result, $MySQLFuncColumns, $BreakColumns);
    updateItem($WorkTable, $strSet, $WorkTableKeyFieldName, $id);
    if(is_callable($CONFIG['AdminAddFuncEditList']))
    {
      $NewRow = getRowByField($WorkTable, $WorkTableKeyFieldName, $id);
      eval($CONFIG['AdminAddFuncEditList'].'();');
    }
  }
  if($imFlag)
  {
  	go_toJVSC(getSameUri());
  }
  else
  {
    go_to(getSameUri());
  }
  exit();
}
elseif($_POST['act'] == 'status')
{
  $result = array(
  	       			$_POST['varname'] => $_POST['varvalue'],
  				);
  if(!isEmptyArr($_SQL_TABLE_FIELDS[$GlobPart]['date']))
  {  	$result['date'] = 'NOW()';
  }
  makeUpdateList($strSet, $result, array('date'));
  updateItem($WorkTable, $strSet, $WorkTableKeyFieldName, $_POST[$WorkTableKeyVarName]);
  go_to(getSameUri());
  exit();
}
elseif($_POST['act'] == 'activate')
{
  $result = array(
  	       			$_POST['task'] => $_POST['subtask'],
  				);
  if(!isEmptyArr($_SQL_TABLE_FIELDS[$GlobPart]['date']))
  {
  	$result['date'] = 'NOW()';
  }
  makeUpdateList($strSet, $result, array('date'));
  foreach($_POST['item'] as $id => $val)
  {
    updateItem($WorkTable, $strSet, $WorkTableKeyFieldName, $id);
  }
  go_to(getSameUri());
  exit();
}
elseif($_POST['act'] == 'copy')
{
  if(count($_POST['item']) != 1)
  {
  	go_to(getSameUri());
    exit();
  }

  $MySQLFuncColumns = array();
  $BreakColumns = array();

  foreach($_POST['item'] as $n => $val)
  {
    $CopyItemID = $val;
    break;
  }
  $ItemFromDB = getRowByField($WorkTable, $WorkTableKeyFieldName, $CopyItemID);
  foreach($_SQL_TABLE_FIELDS[$GlobPart] as $field => $farr)
  {  	if(isBlank($farr['noUseInCopy']))
  	{
  	  if(!isBlank($farr['inCopyValue']))
  	  {  	  	$CopyItem[$field] = $farr['inCopyValue'];
  	  }
  	  elseif(isBlank($farr['inCopyValue']) && !isBlank($ItemFromDB[$field]))
  	  {
  	    $CopyItem[$field] = $ItemFromDB[$field];
  	  }
  	  if($farr['addVarType'] == $CONFIG['VarTypeSQLFunction'] && !isBlank($farr['addVariable']))
      {
      	$MySQLFuncColumns[] = $field;
      	$CopyItem[$field] = $farr['addVariable'];
      }
    }
  }

  makeInsertList($strColumns, $strValues, $CopyItem, $MySQLFuncColumns, $BreakColumns);
  for($i=1; $i<=$_POST['subtask']; $i++)
  {
    insertItem($WorkTable, $strColumns, $strValues);
  }
  go_to(getSameUri());
  exit();
}
elseif($_POST['act'] == 'delete')
{

	foreach($_SQL_TABLE_FIELDS[$GlobPart] as $field => $farr)
	{
		if($farr['type'] == 'image')
	  	{
	  		if($farr['useFTP'] == 'y')
	  		{
	  			require_once __CFG_PATH_LIBS.__CFG_PATH_CORE_CLASSES."class.FTPImage.php";
	  			$ftpi = new FTPImage($farr['ftpServer'], $farr['ftpUserName'], $farr['ftpPassword'], $farr['ftpRootPath']);
	  			
	  			$itemsToDelete = getRowsByFieldArrayValue($WorkTable, $WorkTableKeyFieldName, $_POST['item']);	  			
	  			foreach($itemsToDelete as $arr)
	  			{	  				
	  				$ftpi->deleteFile($arr[$field]);
	  			}
	  		}
	  	}
	}
	if(is_callable($CONFIG['AdminAddFuncDeleteItem']))
	 {	  	foreach($_POST['item'] as $id => $val)
	    {	      eval($CONFIG['AdminAddFuncDeleteItem'].'($id);');
	    }
	}
	delRows($WorkTable, $WorkTableKeyFieldName, $_POST['item']);
	
	go_to(getSameUri());
	exit();
}
elseif(is_callable($CONFIG['ListItemsActionFuncPrefix'].$_POST['act']))
{
  eval($CONFIG['ListItemsActionFuncPrefix'].$_POST['act'].'();');
}

if(!isBlank($_GET[$CONFIG['AdminActionGetVar']]) && is_callable($CONFIG['ListItemsActionFuncPrefix'].$_GET[$CONFIG['AdminActionGetVar']]))
{  eval($CONFIG['ListItemsActionFuncPrefix'].$_GET[$CONFIG['AdminActionGetVar']].'();');
}


if($_FLAGS['NoReadDB'] == __FALSE)
{
  $Items = getListFull($Query['FromTables'], $listInfo, $Query['Fields'], $Query['TabOrder'], $Query['Where'], $Query['GroupBy']);
  $_FLAGS['ListingTab'] = __TRUE;
}

$tpl->assign("Items", $Items);
eval('$PageTitle = '.$PageTitle);
$tpl->assign("PageTitle", $PageTitle);
$tpl->assign_by_ref("ConfFields", $_SQL_TABLE_FIELDS[$GlobPart]);
$tpl->assign_by_ref("ConfEditForms", $_SQL_TABLE_EDIT_FORMS[$GlobPart]);
$tpl->assign_by_ref("GlobPart", $GlobPart);
$tpl->assign("BodyTemplate", $BodyTemplate);

//$Timer->stop($_REQUEST[mode]);
//$Timer->display();
if($tpl->template_exists("admin.".$_REQUEST['mode'].".tpl"))
{
  $_ADMIN_SMARTY_TEMPLATE = "admin.".$_REQUEST['mode'].".tpl";
}
else
{
  $_ADMIN_SMARTY_TEMPLATE = "admin.items.tpl";
}

?>